package com.css.modules.sys.oauth2;

import com.css.common.utils.OAuthInterceptorUtil;
import com.css.common.utils.SsoUrlUtils;
import com.css.modules.app.utils.JwtUtils;
import com.css.modules.sys.service.SysUserTokenService;
import com.google.gson.Gson;
import com.css.common.utils.HttpContextUtils;
import com.css.common.utils.R;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.slw.sso.client.SsoClient;
import org.slw.sso.user.SsoUser;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * oauth2过滤器
 */
public class OAuth2Filter extends AuthenticatingFilter {
    private JwtUtils jwtUtils;
    private SsoUrlUtils ssoUrlUtils;
    private SysUserTokenService sysUserTokenService;

    public OAuth2Filter(JwtUtils jwtUtils, SsoUrlUtils ssoUrlUtils,SysUserTokenService sysUserTokenService) {
        this.jwtUtils = jwtUtils;
        this.ssoUrlUtils = ssoUrlUtils;
        this.sysUserTokenService = sysUserTokenService;
    }

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token
        String token = getRequestToken((HttpServletRequest) request);

        if (StringUtils.isBlank(token)) {
            return null;
        }

        return new OAuth2Token(token);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }

        return false;
    }

    /**
     * 到时候把拦截器写到这里
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token，如果token不存在，直接返回401
        String token = getRequestToken((HttpServletRequest) request);
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        SsoUser ssoUser = SsoClient.getSsoUser(httpRequest, httpResponse);



        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());

        /*if(null == ssoUser && null != token){
            Claims claims = jwtUtils.getClaimByToken(token);
            if (claims == null || jwtUtils.isTokenExpired(claims.getExpiration())) {
                //token失效返回401，弹到登录页面重新登录
                OAuthInterceptorUtil.returnJson(httpResponse, R.error(HttpStatus.SC_UNAUTHORIZED, "invalid token").put("redirectUrl", ssoUrlUtils.getUrl()));
                return false;
            }
            //如果ssouser为空，token不为空并且token未失效的时候直接退出登录，返回给前端退出url
            sysUserTokenService.logout(claims.getSubject());
            OAuthInterceptorUtil.returnJson(httpResponse, R.error(HttpStatus.SC_UNAUTHORIZED, "invalid token").put("redirectUrl", ssoUrlUtils.getQuitUrl()));
            return false;
        }*/

        //拦截器处理
        if(OAuthInterceptorUtil.oAuthInterceptor(httpRequest, httpResponse, token, jwtUtils, ssoUrlUtils, ssoUser)){
            String userId = (String)httpRequest.getAttribute("userId");
            return executeLogin(request, response);
        }else {
            return false;
        }

    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
        try {
            //处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            R r = R.error(HttpStatus.SC_UNAUTHORIZED, throwable.getMessage()).put("redirectUrl", ssoUrlUtils.getUrl());
            String json = new Gson().toJson(r);
            httpResponse.getWriter().print(json);
        } catch (IOException e1) {

        }
        return false;
    }

    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest) {
        //从header中获取token
        String token = httpRequest.getHeader("token");

        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = httpRequest.getParameter("token");
        }

        return token;
    }
}
